<template>
  <div class="commerce-supplier-list">
    <ListTab v-if="!showMobilePage" show-header is-table />
    <div :class="{'mobile-table mobile-pt mobile-min-height':showMobilePage}" class="table-list min-fill-page">
      <div v-if="!showMobilePage" style="position:relative;margin-bottom:16px;">
        <FilterInput
          ref="FilterToolRef"
          v-model="queryForm"
          :filter-list="filterList"
          show-search-btn
          @handelClick="queryClick"
          @queryEmpty="queryEmpty"
          @filterTagStatus="filterTagStatus"/>
        <div class="table-top-opeator-bar">
          <create-button
            v-if="hasRouteAuth('crm:commerceSupplier:add') || isAdmin"
            :add-name="'新建'"
            :create-link-name="'commerceSupplierCreate'"
            class="btn-right-item"/>
          <MoreOpeator
            :list="[
              {label: '导入模板下载', type: 'export', exportApi:'admin/commerce/export/template', exportName:'导入模板'},
            ]"
            style="margin-left:14px;"
          />
          <btnGroup
            v-if="hasRouteAuth('crm:commerceSupplier:import') || isAdmin"
            ref="btnGroupRef"
            :list="[
              {label:'导入', importApi:'/admin/commerce/supplier/import', callback:fetchData, type: 'import' },
            ]"
            style="margin-left:16px;"
          />
        </div>
      </div>
      <div v-loading="listLoading" style="min-height: 300px">
        <u-table
          v-if="list.items.length > 0"
          :data="list.items"
          :height="setTableHeight"
          :row-height="rowHeight()"
          :border="true"
          beautify-table
          header-drag-style
          use-virtual
          class="fb-table"
          element-loading-text="加载中..."
          empty-text="暂无数据"
          header-cell-class-name="order-data-header-cell"
          fit
          hightlight-current-row>
          <u-table-column align="left" label="供应商序号" width="185">
            <template slot-scope="scope">
              <el-tooltip v-if="scope.row.supplierNum || scope.row.supplierNum === 0" :open-delay="800" placement="top-start" effect="dark">
                <div slot="content" style="max-width:200px;">{{ scope.row.supplierNum }}</div>
                <router-link
                  :to="{name: 'commerceSupplierDetail', params: { id: scope.row.id }}"
                  class="project-num">
                  <div class="ellipsis" style="color: #406EFF;">{{ scope.row.supplierNum }}</div>
                </router-link>
              </el-tooltip>
              <div v-else>--</div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="供应商名称" width="240">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.supplierName" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="是否签约" width="200">
            <template slot-scope="scope">
              <span :class="{'red-bg': scope.row.isSign === 0, 'green-bg': scope.row.isSign}" class="bg-text">{{ scope.row.isSign | signStatus }}</span>
            </template>
          </u-table-column>
          <u-table-column align="left" label="供应商名称（备注）" width="200">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.remark" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="合同编号" width="150">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.contactNum" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="标签" width="150">
            <template slot-scope="scope">
              <TagSelect v-model="scope.row.tag" mode="list" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="联系人">
            <template slot-scope="scope">
              <el-tooltip v-if="scope.row.contactPerson" :open-delay="800" placement="top-start" effect="dark">
                <div slot="content" style="max-width:200px;">
                  {{ scope.row.contactPerson }}
                </div>
                <div class="ellipsis">{{ scope.row.contactPerson }}</div>
              </el-tooltip>
              <div v-else>--</div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="联系方式" min-width="150">
            <template slot-scope="scope">
              <SecretText :log-text="`有赞供应商 ${scope.row.supplierNum} 的 联系方式`" :origin-text="scope.row.contactTel" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="订单模式">
            <template slot-scope="scope">
              <div>{{ scope.row.orderModel | orderModelType }}</div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="合作模式">
            <template slot-scope="scope">
              <div>{{ scope.row.cooperationModel | cooperationModelType }}</div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="合作状态">
            <template slot-scope="scope">
              <StatusText :color="['#31cc9c', 'red', '#406eff'][scope.row.cooperationStatus]" :text="scope.row.cooperationStatus | cooperationStatusType" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="进项税">
            <template slot-scope="scope">
              <div v-if="scope.row.inputTax">{{ scope.row.inputTax }} %</div>
              <div v-else>0</div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="销项税">
            <template slot-scope="scope">
              <div v-if="scope.row.outputTax">{{ scope.row.outputTax }} %</div>
              <div v-else>0</div>
            </template>
          </u-table-column>
          <u-table-column :width="operateWidth" label="操作" fixed="right">
            <template slot-scope="scope">
              <div v-if="!showMobilePage" style="display:flex;">
                <div class="button-text" @click="settlement(scope.row)">结算</div>
                <el-dropdown trigger="click">
                  <div class="el-dropdown-link" style="cursor:pointer;">
                    <div class="button-text">更多<i class="el-icon-arrow-down"/></div>
                  </div>
                  <el-dropdown-menu slot="dropdown" style="margin-top:-24px;margin-right:15px;padding: 0;">
                    <el-dropdown-item style="width:100px;text-align: center" @click.native="toCheck(scope.row)">
                      <div>查看</div>
                    </el-dropdown-item>
                    <el-dropdown-item :disabled="!hasRouteAuth('crm:commerceSupplier:edit')" style="width:100px;text-align: center" @click.native="toEdit(scope.row)">
                      <div>编辑</div>
                    </el-dropdown-item>
                    <el-dropdown-item :disabled="!hasRouteAuth('crm:goodsOrder:read')" style="width:100px;text-align: center" @click.native="toGoodsOrder(scope.row)">
                      <div>历史订单</div>
                    </el-dropdown-item>
                    <el-dropdown-item :disabled="!hasRouteAuth('crm:commerceSupplier:del')" style="width:100px;text-align: center" @click.native="toDel(scope.row)">
                      <div>删除</div>
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </div>
              <tableOperateBtn v-else>
                <el-dropdown-item style="width:100px;text-align: center" @click.native="settlement(scope)">
                  <div>结算</div>
                </el-dropdown-item>
                <el-dropdown-item style="width:100px;text-align: center" @click.native="toCheck(scope.row)">
                  <div>查看</div>
                </el-dropdown-item>
                <el-dropdown-item :disabled="!hasRouteAuth('crm:commerceSupplier:edit')" style="width:100px;text-align: center" @click.native="toEdit(scope.row)">
                  <div>编辑</div>
                </el-dropdown-item>
                <el-dropdown-item :disabled="!hasRouteAuth('crm:goodsOrder:read')" style="width:100px;text-align: center" @click.native="toGoodsOrder(scope.row)">
                  <div>历史订单</div>
                </el-dropdown-item>
                <el-dropdown-item :disabled="!hasRouteAuth('crm:commerceSupplier:del')" style="width:100px;text-align: center" @click.native="toDel(scope.row)">
                  <div>删除</div>
                </el-dropdown-item>
              </tableOperateBtn>
            </template>
          </u-table-column>
        </u-table>
        <empty-placeholder v-else-if="!isInit" style="margin-bottom: 24px" />
      </div>
      <el-row v-if="showMobilePage" type="flex" justify="left">
        <el-pagination
          v-show="list.total > 0"
          :current-page="list.page"
          :page-size="list.perPage"
          :total="list.total"
          :page-sizes="[20, 50, 100, 250, 500]"
          :layout="pageLayout"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </el-row>
      <fixed-pagination v-if="list.total > 0 && !showMobilePage || showMobilePage">
        <template v-if="showMobilePage">
          <FilterInput
            ref="FilterToolRef"
            v-model="queryForm"
            :filter-list="filterList"
            show-search-btn
            show-mobile-icon
            @handelClick="queryClick"
            @queryEmpty="queryEmpty"
            @filterTagStatus="filterTagStatus"/>
          <MoreOpeator
            ref="moreOpeatorRef"
            :list="[
              {label: '导入模板下载', type: 'export', exportApi:'admin/commerce/export/template', exportName:'导入模板'},
              { label: '导入', importApi:'/admin/commerce/supplier/import', callback:fetchData, type: 'import', auth: hasRouteAuth('crm:commerceSupplier:import') || isAdmin }
            ]"
            show-mobile-icon
          />
          <createBtn v-if="hasRouteAuth('crm:commerceSupplier:add') || isAdmin" mobile-table @click.native="toCreate" />
        </template>
        <template v-else>
          <div style="flex: 1;" />
          <el-pagination
            v-show="list.total > 0"
            :current-page="list.page"
            :page-size="list.perPage"
            :total="list.total"
            :page-sizes="[20, 50, 100, 250, 500]"
            layout="total, prev, pager, next, sizes, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
        </template>
      </fixed-pagination>
    </div>
  </div>
</template>
<script>
import ClearBtn from '@/components/Common/ClearBtn';
import { getSupplierList, supplierDel } from '@/api/commerce';
import Title from '@/components/Title';
import EmptyPlaceholder from '@/components/EmptyPlaceholder';
import MoreOpeator from '@/components/Common/baseComponent/moreOpeator';
import btnGroup from '@/components/Common/baseComponent/btnGroup';
import createButton from '@/components/CreateButton';
import createBtn from '@/components/Common/baseComponent/createBtn';
import TagSelect from '@/components/Common/tagSelect';
import { orderModelType, cooperationModelType, cooperationStatusType, signStatus } from '@/filters/status';
import { hasRouteAuth } from '@/utils/permission';
import ListTab from '@/components/ListTab';
import { mapState } from 'vuex';
import TableAdaptive from '@/mixins/tableAdaptive';
import { getTagAll } from '@/api/config';
import { TAG_MODULES } from '@/utils/const';
import mobileTable from '@/mixins/mobileTable';

export default {
  name: 'SupplierAccount',
  components: { ClearBtn, MoreOpeator, btnGroup, Title, EmptyPlaceholder, createButton, ListTab, createBtn, TagSelect },
  filters: {
    orderModelType, cooperationModelType, cooperationStatusType, signStatus
  },
  mixins: [TableAdaptive, mobileTable],
  data() {
    return {
      TAG_MODULES,
      isInit: true,
      queryForm: {},
      filterContent: '',
      page: 1,
      perPage: 20,
      list: {
        items: [],
        page: 1,
        perPage: 20,
        total: 0,
        isInint: true
      },
      filterOption: [{
        id: 'supplierName',
        name: '供应商名称'
      }, {
        id: 'supplierNum',
        name: '供应商序号'
      }, {
        id: 'contractNum',
        name: '合同编号'
      }],
      tagTreeList: [],
      listLoading: true,
      statusOptions: [{
        value: 1,
        label: '是'
      }, {
        value: 0,
        label: '否'
      }]
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo
    }),
    isAdmin() {
      return this.userInfo.userName === '管理员';
    },
    tableOutsideHeight() {
      return this.showMobilePage ? 152 : 190;
    },
    filterList() {
      return [
        { keyword: 'supplierName', name: '供应商名称', type: 'input' },
        { keyword: 'supplierNum', name: '供应商序号', type: 'input' },
        { keyword: 'contractNum', name: '合同编号', type: 'input' },
        { keyword: 'tag', name: '标签', valueName: 'id', labelName: 'name',
          childrenVal: 'item', type: 'cascaderSelect', checkStrictly: false, options: this.tagTreeList,
          multiple: true, filterable: true, collapseTags: true
        },
        { keyword: 'isSign', name: '是否签约', type: 'select', options: this.statusOptions }
      ];
    }
  },
  beforeRouteEnter(to, from, next) {
    if (from.name === 'commerceSupplierEdit' || from.name === 'commerceSupplierDetail') {
      to.meta.isChange = true;
    } else {
      to.meta.isChange = false;
    }
    next();
  },
  activated() {
    if (this.$route.meta.isChange) {
      this.fetchData(false);
    } else {
      this.queryEmpty();
    }
    this.queryTagTreeList();
  },
  methods: {
    hasRouteAuth,
    filterKeyChange(e) {
      const queryForm = {};
      queryForm[e] = this.filterContent;
    },
    settlement(item) { // 非订单结算
      const query = { id: item.id, from: 'commerceSupplier', isNotOrder: 1 };
      this.$router.push({
        name: 'supplierCreate', // supplierCreate\supplierDetail
        query
      });
    },
    toEdit(item) {
      this.$router.push({
        name: 'commerceSupplierEdit',
        params: {
          id: item.id
        }
      });
    },
    toCreate() {
      this.$router.push({
        name: 'commerceSupplierCreate'
      });
    },
    toCheck(item) {
      this.$router.push({
        name: 'commerceSupplierDetail',
        params: {
          id: item.id
        }
      });
    },
    toGoodsOrder(item) { // 跳转到商品列表
      this.$router.push({
        name: 'commerceOrder',
        query: {
          supplierName: item.supplierName
        }
      });
    },
    toDel(item) {
      this.$confirm('是否确定删除该供应商', '', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        center: true,
        type: 'warning',
        customClass: ' del-message del-message-cancel',
        iconClass: 'del-icon'
      }).then(() => {
        supplierDel(item.id).then(res => {
          this.$message.success('删除成功');
          if (this.page > 1 && this.perPage * (this.page - 1) + 1 === this.list.total) {
            this.page--;
          }
          this.fetchData();
        }).catch(err => {
          console.error(err);
        });
      }).catch(() => { return false; });
    },
    queryClick() {
      this.fetchData(true);
    },
    queryEmpty() {
      this.queryForm = {};
      this.fetchData(true);
    },
    fetchData(reset = false) {
      if (reset) this.page = 1;
      this.listLoading = true;
      const params = { ...this.queryForm, page: this.page, perPage: this.perPage };
      if (params.tag && params.tag.length > 0) {
        params.tag = params.tag.join(',');
      }
      getSupplierList(params).then(res => {
        this.isInit = false;
        if (res.code === 200) {
          this.list = res.data;
        }
        this.list.isInint = false;
        this.listLoading = false;
      }, result => {
        this.listLoading = false;
      }).catch(e => {
        console.error(e);
      });
    },
    handleSizeChange(val) {
      this.perPage = val;
      this.fetchData(true);
      this.$nextTick(() => {
        document.body.scrollTop = document.documentElement.scrollTop = 0;
      });
    },
    handleCurrentChange(toPage) {
      this.page = toPage;
      this.fetchData();
      this.$nextTick(() => {
        document.body.scrollTop = document.documentElement.scrollTop = 0;
      });
    },
    queryTagTreeList() {
      const params = { type: this.TAG_MODULES.COMMERCE_SUPPLIER };
      getTagAll(params).then(res => {
        this.tagTreeList = (res && res.data) || [];
        this.tagTreeList.forEach(item => {
          if (!item.item) item.disabled = true;
        });
      }).catch(e => {
        console.log(e);
      });
    }
  }
};
</script>
<style lang="scss" scoped>
.commerce-supplier-list {
  .header-form {
    display: flex;
    flex-wrap: wrap;
    .input-box {
      min-width: 742px;
    }
    &::v-deep {
      .query-form .el-form-item {
        margin-right: 16px;
      }
      .input-width-select .el-input__inner {
        width: 200px;
      }
      .changeStatus {
        .el-input input {
          width: 128px;
        }
      }
    }
  }
  .table-list {
    margin: 16px 16px 0 16px;
    background-color: #fff;
    padding: 20px 20px 55px 20px;
    overflow: hidden;
  }
  .pagination-area {
    display: flex;
    justify-content: flex-end;
    align-items: center;
  }
  .bg-text {
    width: 64px;
    height: 20px;
    padding: 0 6px;
    line-height: 20px;
    border-radius: 10px;
    font-size: 12px;
    text-align: center;
  }
  .green-bg {
    background: #e2f8f2;
    color: #31cc9c;
  }
  .red-bg {
    background: #F8E2E2;
    color: #FF4E5F;
  }
}
.el-dropdown-link {
  display: block;
  position: relative;
  padding-left:6px;
  margin-left: 6px;
  &::before {
    content: '';
    position: absolute;
    left: 0;
    top: 50%;
    margin-top: -7px;
    width: 1px;
    background: #ddd;
    height: 14px;
  }
}
</style>
